import type { Directive, DirectiveBinding } from 'vue';

export const imgLazy = {
  mounted(el: HTMLImageElement, binding: DirectiveBinding) {
    let isLoading = false;

    const loadImage = () => {
      if (isLoading) return;
      isLoading = true;
      const img = new Image();
      img.src = binding.value;
      img.addEventListener('load', () => {
        el.src = img.src;
        isLoading = false;
      });
      img.addEventListener('error', () => {
        // 图片加载失败的处理
        el.src = 'path/to/default/image.jpg'; // 设置一个默认图片
        isLoading = false;
      });
    };

    // 明确指定 entries 和 observer 的类型
    const handleIntersect = (
      entries: IntersectionObserverEntry[],
      observer: IntersectionObserver,
    ) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          loadImage();
          observer.unobserve(el); // 图片加载后停止观察
        }
      });
    };

    const observer = new IntersectionObserver(handleIntersect, {
      root: null, // 使用视口作为根元素
      threshold: 0.1, // 当至少有10%的元素在视口内时触发回调
    });

    observer.observe(el); // 开始观察元素
  },
};
export const lazy = {
  mounted(el: Directive, binding: DirectiveBinding, vnode: any) {
    console.log('mounted', el, binding, vnode);
  },
};
